package GUI;

import java.awt.Color;
import java.util.Random;

import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;

@SuppressWarnings("serial")
public class Player extends JPanel{
	private String name;
	private boolean active, hasTurn, isOwner, updatedBid;
	private int cash, latestBid, minimumBid, playerIndex;
	private JLabel nameLabel, stateLabel;
	
	public Player(String name, int cash, boolean isOwner){
		this.isOwner = isOwner;
		this.playerIndex = -1;
		this.cash = cash;
		this.name = name;
		this.active = true;
		this.hasTurn = false;
		this.updatedBid = true;
		this.nameLabel = new JLabel(name);
		this.stateLabel = new JLabel();
		this.latestBid = minimumBid = 0;
		this.setForeground(Color.blue);
		nameLabel.setFont(getFont().deriveFont(15));
		this.present();
	}
	public int getAmtLeft(){
		return cash;
	}
	public void setIndex(int index){
		playerIndex = index;
	}
	public int getIndex(){
		return playerIndex;
	}
	public int bid(int bidAmt){
		if(!active)return 0;
		else if((bidAmt < minimumBid)){
			active = false;
			return 0;
		}
		latestBid += bidAmt;
		cash -= bidAmt;
		return latestBid;
	}
	public void call(){
		updatedBid = true;
		bid(minimumBid);
	}
	public int raise(int amt){
		updatedBid = true;
		return bid(amt);
	}
	public String getName(){
		return name;
	}
	public boolean notifyMinimum(int min){
		minimumBid = min;
		if(!active){
			this.updateState();
			this.setForeground(Color.RED);
			return false;
		}
		else if(cash < min){
			active = false;
			return false;
		}
		return true;
	}
	public boolean hasTurn(){
		return hasTurn;
	}
	public boolean isOwner(){
		return isOwner;
	}
	public boolean isActive(){
		return active;
	}
	public void inactiveate(){
		active = false;
	}
	public void takeTurn(boolean automated){
		hasTurn = true;
		if(!active){
			releaseTurn();
		}else{
			this.setForeground(Color.WHITE);
			this.setBackground(Color.GREEN);
			if(automated){
				Random rand = new Random(System.currentTimeMillis());
				bid(minimumBid + rand.nextInt(3));
			}else{
				updatedBid = false;
			}
		}

	}
	public int getNewBid(){
		return updatedBid?latestBid:-1;
	}
	private void present(){
		this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
		this.add(nameLabel);
		this.add(stateLabel);
	}
	public String getStatus(){
		if(active){
			return "   bid: <"+this.latestBid+">";
		}else{
			return " has LEFT THE TABLE";
		}
	}
	public void updateState(){
		this.stateLabel.setText(getStatus());
		if(!this.active){
			this.setForeground(Color.yellow);
		}else{
			this.setForeground(Color.BLACK);
			this.setBackground(Color.WHITE);
		}
	}
	public void releaseTurn(){
		updateState();
		hasTurn =  false;
	}
}
